// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import Client from '@api/map/api/AreaMapApi'

import ComClass from '@api/ComQuery'
import ListClass from '@api/map/model/QueryAreaMapDeviceListReq'
import InfoClass from '@api/map/model/QueryAreaMapReq'
import OneClass from '@api/map/model/QueryAreaMapDeviceDetailReq'

const CLIENT = CORE.grpcCLIENT(Client)
const COM = [ComClass, 'comQuery']

const transList = (arr, { rootState: { param: { deviceType } } }) => {
  const trans = (item, key) => item[key] && item[key] !== '0' ? +item[key].slice(0, -1) : null // 只有 % 前面的浮点数字
  arr.forEach((item) => {
    item.detailId = item.deviceId // 详情 ID
    item.site = JSON.parse(item.siteJson || '{}')
    item.left = trans(item, 'longitude')
    item.top = trans(item, 'latitude')
  })
  return deviceType ? arr.filter((item) => item.deviceTypeId === `${deviceType}`) : arr
}

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 信息 —————————————————————————————— //

  validInfoParam(infoParam) {
    return infoParam.areaId && infoParam.areaId !== '0'
  },
  async getInfo(infoParam, TIP = '信息') {
    const DTO = CORE.grpcDTO(InfoClass, infoParam)
    const { content = {}, rootDto = {} } = await CORE.grpc(TIP, CLIENT, 'queryAreaMap', DTO)
    return { ...content, rootDto }
  },
  transInfo({ rootDto, ...obj }) {
    if (CORE.isEmpty(obj)) return {}

    if (obj.mapParent === 1) {
      obj.fileUrl = rootDto.fileUrl
      obj.mapName = rootDto.mapName
      obj.mapRate = rootDto.mapRate
    }

    const [before, after] = obj.mapRate.split(':')
    obj.rateBefore = +before
    obj.rateAfter = +after

    return obj
  },

  // —————————————————————————————— 列表 —————————————————————————————— //

  validParam(param) {
    return param.areaMapId && param.deviceCategoryId && param.deviceCategoryId !== 'line'
  },
  async getList(param, TIP = '查询列表') {
    const DTO = CORE.grpcDTO(ListClass, param, COM)
    const resp = await CORE.grpc(TIP, CLIENT, 'queryChildrenAreaMapDeviceList', DTO)
    return [resp.comQuery.totalCount, resp.content || []]
  },
  transList,

  // —————————————————————————————— 下拉框 —————————————————————————————— //

  validSelectParam(paramSelect) {
    return paramSelect.areaMapId && paramSelect.deviceCategoryId
  },
  async getSelect(selectParam, TIP = '查询下拉框') {
    const DTO = CORE.grpcDTO(ListClass, selectParam, COM)
    const resp = await CORE.grpc(TIP, CLIENT, 'queryChildrenAreaMapDeviceList', DTO)
    return resp.content || []
  },
  transSelect: transList,

  // —————————————————————————————— 单项 —————————————————————————————— //

  async getOne({ id }, TIP = '查询详情') {
    const DTO = CORE.grpcDTO(OneClass, { id })
    const resp = await CORE.grpc(TIP, CLIENT, 'queryAreaMapDeviceDetail', DTO)
    return resp.content || {}
  },
}
